﻿$(function () {

    function split(val) {
        return val.split(/,\s*/);
    }
    function extractLast(term) {
        return split(term).pop();
    }

    function autoCompleteMultiOptions(elementId, jsonUrl, getName)
    {
    	$(elementId)
			// don't navigate away from the field on tab when selecting an item
			.bind("keydown", function (event) {
				if (event.keyCode === $.ui.keyCode.TAB &&
					$(this).autocomplete("instance").menu.active) {
					event.preventDefault();
				}
			})
			.autocomplete({
				source: function (request, response) {
					$.getJSON(jsonUrl + extractLast(request.term), function (data) {
						console.log(data);

						var elements = [];
						$.each(data, function (key, item) {
							elements.push(getName(item));
						});

						response(elements.slice(0, 10));
					})
				},
				search: function () {
					// custom minLength
					var term = extractLast(this.value);
				},
				focus: function () {
					// prevent value inserted on focus
					return false;
				},
				select: function (event, ui) {
					var terms = split(this.value);
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push(ui.item.value);
					// add placeholder to get the comma-and-space at the end
					terms.push("");
					this.value = terms.join(", ");
					return false;
				}
			});
    }

    autoCompleteMultiOptions("#titleAuthors", "/api/author/?q=", function (item) {
    	return item.Author.Name;
    });
    autoCompleteMultiOptions("#titleEditors", "/api/author/?q=", function (item) {
        return item.Author.Name;
    });
    autoCompleteMultiOptions("#titleTopics", "/api/topic/?q=", function (item) {
    	return item.Topic.TopicName;
    });

    

    /*$("#titleAuthors")
        // don't navigate away from the field on tab when selecting an item
        .bind("keydown", function (event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).autocomplete("instance").menu.active) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function (request, response) {
                $.getJSON("/api/author/?q=" + extractLast(request.term), function (data) {
                    console.log(data);

                    var authors = [];
                    $.each(data, function (key, item) {
                        authors.push(item.Author.FirstName + " " + item.Author.LastName);
                    });

                    response(authors.slice(0,10));
                })
            },
            search: function () {
                // custom minLength
                var term = extractLast(this.value);
            },
            focus: function () {
                // prevent value inserted on focus
                return false;
            },
            select: function (event, ui) {
                var terms = split(this.value);
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });*/


    $("#titleLocationCategory").autocomplete({
        source: function (request, response) {
            console.log(request);
            $.getJSON("/api/loanableLocationCategory/?q=" + request.term, function (data) {
                console.log(data);
                response(data.slice(0, 15));
            })
        },
        minLength: 1,
        select: function (event, ui) {
            console.log(ui.item);
            if (ui.item) {
                $('#titleLocationCategory').val(ui.item.value);
            }
        }
    });

    $("#titlePublisher").autocomplete({
        source: function (request, response) {
            console.log(request);
            $.getJSON("/api/publisher/?q=" + request.term, function (data) {
                console.log(data);
                response(data.slice(0, 10));
            })
        },
        minLength: 1,
        select: function (event, ui) {
            console.log(ui.item);
            if (ui.item) {
                $('#Publisher').val(ui.item.value);
            }
        }
    });

    $("#titleTitle").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/api/search/?searchOption=Title&searchTerm=" + encodeURIComponent(request.term),
                success: function (data) {
                    var resList = [];
                    $.each(data.Titles, function (i, a) {
                        a.label = a.Title.BookTitle + " — ";
                        if (a.Authors != null)
                        {
                            $.each(a.Authors, function (i, b) {
                                a.label = a.label + b.Name + ", ";
                            });
                        }
                        a.label = a.label + a.Title.EditionYear;

                        a.titleID = a.Title.TitleId;
                        resList.push(a);
                    });

                    if (data.Titles.length < 10) {
                        $.ajax({
                            url: "https://www.googleapis.com/books/v1/volumes/",
                            dataType: "jsonp",
                            data: {
                                q: request.term,
                                fields: "items(id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate)"
                            },
                            minLength: 2,
                            success: function (data) {
                                $.each(data.items, function (i, a) {
                                    a.label = a.volumeInfo.title + " — " + a.volumeInfo.authors + ((a.volumeInfo.publishedDate == undefined) ? "" : ", " + a.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                                    a.titleID = a.id;
                                    resList.push(a);
                                });
                                response(resList.slice(0, 10));
                            }
                        });
                    }                            

                    response(resList.slice(0, 10));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            //If title is from Google
            if (ui.item.Title == null) {
                $.ajax({
                    url: "https://www.googleapis.com/books/v1/volumes/" + encodeURIComponent(ui.item.titleID),
                    dataType: "jsonp",
                    data: {
                        fields: "id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate"
                    },
                    success: function (data) {
                        if (data.volumeInfo.industryIdentifiers != null) {
                            if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            else if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[1].identifier);
                            else if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[1].identifier);
                        };

                        $.each(data.volumeInfo.authors, function (i, a) {
                            if(i==0)
                                $('#titleAuthors').val(a);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a);
                        });
                        
                        $('#titleTitle').val(data.volumeInfo.title);
                        //Only year                        
                        $('#titlePublicationYear').val(data.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                        $('#titlePublisher').val(data.volumeInfo.publisher);
                    }
                });
            }

                //If title is from DB
            else if (ui.item.Title != null) {
                $.ajax({
                    url: "/api/title/" + encodeURIComponent(ui.item.titleID),
                    success: function (data) {
                        $.each(data.Authors, function (i, a) {
                            if (i == 0)
                                $('#titleAuthors').val(a.Name);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a.Name);
                        });

                        $.each(data.Topics, function (i, a) {
                        	if (i == 0)
                        		$('#titleTopics').val(a.TopicName);
                        	else
                        		$('#titleTopics').val($('#titleTopics').val() + ", " + a.TopicName);
                        });

                        $('#titleTitle').val(data.Title.BookTitle);                    
                        $('#titlePublicationYear').val(data.Title.EditionYear);
                        $('#titlePublisher').val(data.Title.Publisher.Name);
                        $('#titleISBN13').val(data.Title.ISBN13);
                        $('#titleISBN10').val(data.Title.ISBN10);
                        $('#titleFirstEditionYear').val(data.Title.FirstEditionYear);
                        $('#titleEdition').val(data.Title.EditionNumber);
                    }
                });
            }


                
        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            var width = $(".ui-autocomplete-input").innerWidth();
            $('.ui-menu').css('max-width', width);
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });

    $("#titleISBN13").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/api/search/?searchOption=ISBN-13&searchTerm=" + encodeURIComponent(request.term),
                success: function (data) {
                    var resList = [];
                    $.each(data.Titles, function (i, a) {
                        a.label = a.Title.BookTitle + " — ";
                        if (a.Authors != null) {
                            $.each(a.Authors, function (i, b) {
                                a.label = a.label + b.Name + ", ";
                            });
                        }
                        a.label = a.label + a.Title.EditionYear;

                        a.titleID = a.Title.TitleId;
                        resList.push(a);
                    });

                    if (data.Titles.length < 10) {
                        $.ajax({
                            url: "https://www.googleapis.com/books/v1/volumes/",
                            dataType: "jsonp",
                            data: {
                                q: request.term,
                                fields: "items(id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate)"
                            },
                            minLength: 2,
                            success: function (data) {
                                $.each(data.items, function (i, a) {
                                    a.label = a.volumeInfo.title + " — " + a.volumeInfo.authors + ((a.volumeInfo.publishedDate == undefined) ? "" : ", " + a.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                                    a.titleID = a.id;
                                    resList.push(a);
                                });
                                response(resList.slice(0, 10));
                            }
                        });
                    }

                    response(resList.slice(0, 10));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            //If title is from Google
            if (ui.item.Title == null) {
                $.ajax({
                    url: "https://www.googleapis.com/books/v1/volumes/" + encodeURIComponent(ui.item.titleID),
                    dataType: "jsonp",
                    data: {
                        fields: "id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate"
                    },
                    success: function (data) {
                        if (data.volumeInfo.industryIdentifiers != null) {
                            if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            else if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[1].identifier);
                            else if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[1].identifier);
                        };

                        $.each(data.volumeInfo.authors, function (i, a) {
                            if (i == 0)
                                $('#titleAuthors').val(a);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a);
                        });

                        $('#titleTitle').val(data.volumeInfo.title);
                        //Only year                        
                        $('#titlePublicationYear').val(data.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                        $('#titlePublisher').val(data.volumeInfo.publisher);
                    }
                });
            }

                //If title is from DB
            else if (ui.item.Title != null) {
                $.ajax({
                    url: "/api/title/" + encodeURIComponent(ui.item.titleID),
                    success: function (data) {
                        $.each(data.Authors, function (i, a) {
                            if (i == 0)
                                $('#titleAuthors').val(a.Name);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a.Name);
                        });

                        $.each(data.Topics, function (i, a) {
                            if (i == 0)
                                $('#titleTopics').val(a.TopicName);
                            else
                                $('#titleTopics').val($('#titleTopics').val() + ", " + a.TopicName);
                        });

                        $('#titleTitle').val(data.Title.BookTitle);
                        $('#titlePublicationYear').val(data.Title.EditionYear);
                        $('#titlePublisher').val(data.Title.Publisher.Name);
                        $('#titleISBN13').val(data.Title.ISBN13);
                        $('#titleISBN10').val(data.Title.ISBN10);
                        $('#titleFirstEditionYear').val(data.Title.FirstEditionYear);
                        $('#titleEdition').val(data.Title.EditionNumber);
                    }
                });
            }



        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            var width = $(".ui-autocomplete-input").innerWidth();
            $('.ui-menu').css('max-width', width);
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });

    $("#titleISBN10").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/api/search/?searchOption=ISBN-10&searchTerm=" + encodeURIComponent(request.term),
                success: function (data) {
                    var resList = [];
                    $.each(data.Titles, function (i, a) {
                        a.label = a.Title.BookTitle + " — ";
                        if (a.Authors != null) {
                            $.each(a.Authors, function (i, b) {
                                a.label = a.label + b.Name + ", ";
                            });
                        }
                        a.label = a.label + a.Title.EditionYear;

                        a.titleID = a.Title.TitleId;
                        resList.push(a);
                    });

                    if (data.Titles.length < 10) {
                        $.ajax({
                            url: "https://www.googleapis.com/books/v1/volumes/",
                            dataType: "jsonp",
                            data: {
                                q: request.term,
                                fields: "items(id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate)"
                            },
                            minLength: 2,
                            success: function (data) {
                                $.each(data.items, function (i, a) {
                                    a.label = a.volumeInfo.title + " — " + a.volumeInfo.authors + ((a.volumeInfo.publishedDate == undefined) ? "" : ", " + a.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                                    a.titleID = a.id;
                                    resList.push(a);
                                });
                                response(resList.slice(0, 10));
                            }
                        });
                    }

                    response(resList.slice(0, 10));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            //If title is from Google
            if (ui.item.Title == null) {
                $.ajax({
                    url: "https://www.googleapis.com/books/v1/volumes/" + encodeURIComponent(ui.item.titleID),
                    dataType: "jsonp",
                    data: {
                        fields: "id, volumeInfo/title, volumeInfo/authors, volumeInfo/industryIdentifiers, volumeInfo/publisher, volumeInfo/publishedDate"
                    },
                    success: function (data) {
                        if (data.volumeInfo.industryIdentifiers != null) {
                            if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            else if (data.volumeInfo.industryIdentifiers[0] != null && data.volumeInfo.industryIdentifiers[0].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[0].identifier);
                            if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_10")
                                $('#titleISBN10').val(data.volumeInfo.industryIdentifiers[1].identifier);
                            else if (data.volumeInfo.industryIdentifiers[1] != null && data.volumeInfo.industryIdentifiers[1].type == "ISBN_13")
                                $('#titleISBN13').val(data.volumeInfo.industryIdentifiers[1].identifier);
                        };

                        $.each(data.volumeInfo.authors, function (i, a) {
                            if (i == 0)
                                $('#titleAuthors').val(a);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a);
                        });

                        $('#titleTitle').val(data.volumeInfo.title);
                        //Only year                        
                        $('#titlePublicationYear').val(data.volumeInfo.publishedDate.replace(/\D/g, '').slice(0, 4));
                        $('#titlePublisher').val(data.volumeInfo.publisher);
                    }
                });
            }

                //If title is from DB
            else if (ui.item.Title != null) {
                $.ajax({
                    url: "/api/title/" + encodeURIComponent(ui.item.titleID),
                    success: function (data) {
                        $.each(data.Authors, function (i, a) {
                            if (i == 0)
                                $('#titleAuthors').val(a.Name);
                            else
                                $('#titleAuthors').val($('#titleAuthors').val() + ", " + a.Name);
                        });

                        $.each(data.Topics, function (i, a) {
                            if (i == 0)
                                $('#titleTopics').val(a.TopicName);
                            else
                                $('#titleTopics').val($('#titleTopics').val() + ", " + a.TopicName);
                        });

                        $('#titleTitle').val(data.Title.BookTitle);
                        $('#titlePublicationYear').val(data.Title.EditionYear);
                        $('#titlePublisher').val(data.Title.Publisher.Name);
                        $('#titleISBN13').val(data.Title.ISBN13);
                        $('#titleISBN10').val(data.Title.ISBN10);
                        $('#titleFirstEditionYear').val(data.Title.FirstEditionYear);
                        $('#titleEdition').val(data.Title.EditionNumber);
                    }
                });
            }



        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            var width = $(".ui-autocomplete-input").innerWidth();
            $('.ui-menu').css('max-width', width);
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });

});